package tt.dz.egobus.servicemanager.business.filter;

import tt.dz.egobus.api.managerservice.manager.AddressUnit;
import tt.dz.egobus.api.managerservice.manager.RequestTask;
import tt.dz.egobus.api.managerservice.manager.UserRequestAddressInfo;
import tt.dz.egobus.api.managerservice.manager.UserRequestTypeInfo;
import tt.dz.egobus.servicemanager.bean.CornConverter;
import tt.dz.egobus.servicemanager.business.convert.BespeakTimeRedisRestoreConvertor;
import tt.dz.egobus.servicemanager.business.distance.PointFilter;
import tt.dz.egobus.servicemanager.business.point.BusPoint;
import tt.dz.egobus.servicemanager.entities.DriverRegisterBusRelative;
import tt.dz.egobus.servicemanager.service.GrabRedisBusinessWorkCacheService;

import java.util.Date;

/**
 * @author Anson
 * @date 17-8-29
 * @name 预约的匹配器
 * @since 1.0.7
 */
public class BespeakBusPointMatchHandler implements UserRequestBusPointMatchHandler {

    private final GrabRedisBusinessWorkCacheService businessWorkCacheService;
    private final RequestTask requestTask;

    public BespeakBusPointMatchHandler(GrabRedisBusinessWorkCacheService businessWorkCacheService,
                                       RequestTask requestTask) {
        this.businessWorkCacheService = businessWorkCacheService;
        this.requestTask = requestTask;
    }

    @Override
    public UserRequestTypeInfo.UserRequestType getRequestType() {
        return UserRequestTypeInfo.UserRequestType.BESPEAK;
    }

    @Override
    public BusPoint[] filter(PointFilter filter) {
        BusPoint[] bp = new BusPoint[0];
        PointChainFilter originalFilter = this.getFilter();
        if (filter != null) {
            originalFilter.add(filter);
        }
        UserRequestAddressInfo userRequestAddressInfo = requestTask.getUserRequestAddressInfo();
        AddressUnit userOnStartAddress = userRequestAddressInfo.getRequestOnStartAddress();
        double x = userOnStartAddress.getX();
        double y = userOnStartAddress.getY();
        BusPoint[] availableBusPoints = businessWorkCacheService.filterMaxLength(x, y, originalFilter,
                DriverRegisterBusRelative.RelativeStatus.ACTIVE);
        return availableBusPoints == null ? bp : availableBusPoints;
    }


    private PointChainFilter getFilter() {
        int businessCode = requestTask.getBusinessCode();
        PointChainFilter pointChainFilter = new PointChainFilter();
        //预约添加了对预约时间的控制
        //预约添加了对服务号的控制
        CornConverter<Date, String> cornConverter = new BespeakTimeRedisRestoreConvertor();
        String bespeakDateStr = cornConverter.convertCornA().convert(new Date(requestTask.getUserRequestInfo().getBespeakTime()));
        pointChainFilter.add(new
                BusinessCodeValidateFilter(businessCode));
        pointChainFilter.add(new
                BespeakDateDriverPointFilter(businessWorkCacheService, bespeakDateStr));
        return pointChainFilter;
    }


}
